import React, { useEffect, useState } from "react";
import { List, message, Avatar, Badge } from "antd";
import { useHistory } from "react-router-dom";
import { fetchCustomerServiceList } from "../../api/customerService";

const CustomerServiceList = () => {
  const [loading, setLoading] = useState(false);
  const [messageList, setMessageList] = useState([]);
  const history = useHistory();

  useEffect(() => {
    loadMessageList();
  }, []);

  const loadMessageList = async () => {
    setLoading(true);
    try {
      const response = await fetchCustomerServiceList();
      if (Array.isArray(response.data)) {
        console.log("Processed message list:", response.data);
        setMessageList(response.data);
      } else {
        console.error("Invalid response data:", response.data);
        message.error("获取客服消息列表失败: 无效的数据格式");
        setMessageList([]);
      }
    } catch (error) {
      console.error("Error fetching customer service list:", error);
      message.error("获取客服消息列表失败: " + (error.message || "未知错误"));
      setMessageList([]);
    } finally {
      setLoading(false);
    }
  };

  const handleItemClick = (conversationId) => {
    if (conversationId) {
      history.push(`/customerService/chat/${conversationId}`);
    } else {
      console.error("Invalid conversationId:", conversationId);
      message.error("无法打开聊天: 无效的会话ID");
    }
  };

  return (
    <List
      loading={loading}
      itemLayout="horizontal"
      dataSource={messageList}
      renderItem={(item) => (
        <List.Item
          key={item.conversation_id}
          onClick={() => handleItemClick(item.conversation_id)}
        >
          <List.Item.Meta
            avatar={<Avatar>{item.userName ? item.userName[0] : "U"}</Avatar>}
            title={item.userName || "Unknown User"}
            description={item.lastMessage || "No message"}
          />
          <div>
            {item.unreadCount > 0 && (
              <Badge count={item.unreadCount} style={{ marginRight: "10px" }} />
            )}
            {item.timestamp && (
              <span>{new Date(item.timestamp).toLocaleString()}</span>
            )}
          </div>
        </List.Item>
      )}
    />
  );
};

export default CustomerServiceList;
